<template>
  <div class="reset-password-container">
    <div class="reset-password-wrapper">
      <div class="reset-password-card">
        <!-- 头部 -->
        <div class="reset-password-header">
          <div class="logo">
            <img src="/logo.svg" alt="Logo" />
          </div>
          <h2 class="title">重置密码</h2>
          <p class="subtitle">请设置您的新密码</p>
        </div>

        <!-- 加载状态 -->
        <div v-if="validating" class="validating">
          <el-icon class="loading-icon"><Loading /></el-icon>
          <p>正在验证重置链接...</p>
        </div>

        <!-- 无效链接 -->
        <div v-else-if="!isValidToken" class="invalid-token">
          <el-icon class="error-icon"><CircleClose /></el-icon>
          <h3>重置链接无效</h3>
          <p>该重置链接已过期或无效，请重新申请密码重置。</p>
          <el-button type="primary" @click="goToForgotPassword">
            重新申请
          </el-button>
        </div>

        <!-- 重置密码表单 -->
        <el-form
          v-else
          ref="resetPasswordFormRef"
          :model="resetPasswordForm"
          :rules="resetPasswordRules"
          size="large"
          label-position="top"
          class="reset-password-form"
        >
          <!-- 新密码 -->
          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model="resetPasswordForm.newPassword"
              type="password"
              placeholder="请输入新密码（6-20字符）"
              show-password
              clearable
              :prefix-icon="Lock"
              @input="onPasswordChange"
            />
            <div v-if="passwordStrengthTip" class="password-strength">
              {{ passwordStrengthTip }}
            </div>
          </el-form-item>

          <!-- 确认密码 -->
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="resetPasswordForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              show-password
              clearable
              :prefix-icon="Lock"
              @keyup.enter="handleResetPassword"
            />
          </el-form-item>

          <!-- 重置按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              size="large"
              :loading="resetLoading"
              :disabled="resetLoading"
              class="reset-btn"
              @click="handleResetPassword"
            >
              {{ resetLoading ? "重置中..." : "重置密码" }}
            </el-button>
          </el-form-item>

          <!-- 返回登录 -->
          <div class="back-to-login">
            <router-link to="/user/login" class="link">
              <el-icon><ArrowLeft /></el-icon>
              返回登录
            </router-link>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules
} from "element-plus";
import { Lock, Loading, CircleClose, ArrowLeft } from "@element-plus/icons-vue";
import {
  validateResetTokenApi,
  resetPasswordApi,
  UserAuthUtils,
  type ResetPasswordRequest
} from "@/api/user-auth";

defineOptions({
  name: "ResetPassword"
});

const router = useRouter();
const route = useRoute();

// 表单引用
const resetPasswordFormRef = ref<FormInstance>();

// 表单数据
const resetPasswordForm = reactive<ResetPasswordRequest>({
  resetToken: "",
  newPassword: "",
  confirmPassword: ""
});

// 状态管理
const validating = ref(true);
const isValidToken = ref(false);
const resetLoading = ref(false);

// 计算属性
const passwordStrengthTip = computed(() => {
  if (!resetPasswordForm.newPassword) return "";
  return UserAuthUtils.getPasswordStrengthTip(resetPasswordForm.newPassword);
});

// 表单验证规则
const resetPasswordRules: FormRules = {
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (!UserAuthUtils.validatePassword(value)) {
          callback(new Error("密码长度应为6-20字符"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (
          !UserAuthUtils.validatePasswordMatch(
            resetPasswordForm.newPassword,
            value
          )
        ) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
};

// 验证重置令牌
const validateToken = async () => {
  const token = route.query.token as string;

  if (!token) {
    isValidToken.value = false;
    validating.value = false;
    return;
  }

  try {
    const response = await validateResetTokenApi(token);

    if (response.code === 200) {
      isValidToken.value = true;
      resetPasswordForm.resetToken = token;
    } else {
      isValidToken.value = false;
      ElMessage.error(response.message || "重置链接无效");
    }
  } catch (error) {
    isValidToken.value = false;
    ElMessage.error(UserAuthUtils.formatErrorMessage(error));
  } finally {
    validating.value = false;
  }
};

// 密码变化处理
const onPasswordChange = () => {
  // 触发确认密码验证
  if (resetPasswordForm.confirmPassword) {
    resetPasswordFormRef.value?.validateField("confirmPassword");
  }
};

// 处理密码重置
const handleResetPassword = async () => {
  if (!resetPasswordFormRef.value) return;

  try {
    const valid = await resetPasswordFormRef.value.validate();
    if (!valid) return;

    resetLoading.value = true;

    const response = await resetPasswordApi(resetPasswordForm);

    if (response.code === 200) {
      await ElMessageBox.alert("密码重置成功！请使用新密码登录。", "重置成功", {
        confirmButtonText: "去登录",
        type: "success"
      });

      // 跳转到登录页面
      router.push("/user/login");
    } else {
      ElMessage.error(response.message || "密码重置失败");
    }
  } catch (error) {
    ElMessage.error(UserAuthUtils.formatErrorMessage(error));
  } finally {
    resetLoading.value = false;
  }
};

// 跳转到忘记密码页面
const goToForgotPassword = () => {
  router.push("/user/forgot-password");
};

// 组件挂载时验证令牌
onMounted(() => {
  validateToken();
});
</script>

<style scoped lang="scss">
@keyframes spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

// 响应式设计
@media (width <= 640px) {
  .reset-password-container {
    padding: 16px;
  }

  .reset-password-card {
    padding: 24px;
  }

  .reset-password-header {
    margin-bottom: 24px;

    .title {
      font-size: 24px;
    }

    .subtitle {
      font-size: 14px;
    }
  }
}

// 暗色主题适配
@media (prefers-color-scheme: dark) {
  .reset-password-card {
    color: #f9fafb;
    background: #1f2937;
  }

  .reset-password-header {
    .title {
      color: #f9fafb;
    }

    .subtitle {
      color: #d1d5db;
    }
  }

  .reset-password-form {
    :deep(.el-form-item__label) {
      color: #e5e7eb;
    }
  }

  .validating p {
    color: #d1d5db;
  }

  .invalid-token {
    h3 {
      color: #f9fafb;
    }

    p {
      color: #d1d5db;
    }
  }
}

.reset-password-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding: 20px;
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
}

.reset-password-wrapper {
  width: 100%;
  max-width: 450px;
}

.reset-password-card {
  padding: 40px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgb(0 0 0 / 10%);
  backdrop-filter: blur(10px);
}

.reset-password-header {
  margin-bottom: 32px;
  text-align: center;

  .logo {
    margin-bottom: 16px;

    img {
      width: 64px;
      height: 64px;
    }
  }

  .title {
    margin: 0 0 8px;
    font-size: 28px;
    font-weight: 600;
    color: #1f2937;
  }

  .subtitle {
    margin: 0;
    font-size: 16px;
    color: #6b7280;
  }
}

.validating {
  padding: 40px 20px;
  text-align: center;

  .loading-icon {
    margin-bottom: 16px;
    font-size: 48px;
    color: #409eff;
    animation: spin 1s linear infinite;
  }

  p {
    margin: 0;
    font-size: 16px;
    color: #6b7280;
  }
}

.invalid-token {
  padding: 40px 20px;
  text-align: center;

  .error-icon {
    margin-bottom: 16px;
    font-size: 48px;
    color: #ef4444;
  }

  h3 {
    margin: 0 0 12px;
    font-size: 20px;
    font-weight: 600;
    color: #1f2937;
  }

  p {
    margin: 0 0 24px;
    font-size: 16px;
    line-height: 1.5;
    color: #6b7280;
  }
}

.reset-password-form {
  .el-form-item {
    margin-bottom: 20px;

    :deep(.el-form-item__label) {
      margin-bottom: 8px;
      font-weight: 500;
      color: #374151;
    }

    :deep(.el-input__wrapper) {
      border-radius: 8px;
      box-shadow: 0 1px 3px rgb(0 0 0 / 10%);
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 4px 6px rgb(0 0 0 / 10%);
      }

      &.is-focus {
        box-shadow: 0 0 0 2px rgb(64 158 255 / 20%);
      }
    }
  }

  .password-strength {
    margin-top: 4px;
    font-size: 12px;
    color: #6b7280;
  }

  .reset-btn {
    width: 100%;
    height: 48px;
    font-size: 16px;
    font-weight: 500;
    background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
    border: none;
    border-radius: 8px;
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 8px 16px rgb(64 158 255 / 30%);
      transform: translateY(-2px);
    }

    &:active {
      transform: translateY(0);
    }

    &.is-loading,
    &.is-disabled {
      box-shadow: none;
      transform: none;
    }
  }

  .back-to-login {
    margin-top: 24px;
    text-align: center;

    .link {
      display: inline-flex;
      gap: 8px;
      align-items: center;
      font-weight: 500;
      color: #409eff;
      text-decoration: none;
      transition: color 0.3s ease;

      &:hover {
        color: #337ecc;
      }

      .el-icon {
        font-size: 16px;
      }
    }
  }
}
</style>
